package com.road.spider.execution;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.road.httpclient.utils.AbstractClient;
import com.road.spider.JsoupRequest;

/**
 * @Description :
 * @FileName: ParserAction.java
 * @Author :WeiHui.Zhang
 * @Data : 2016年3月10日 下午7:31:38
 * @Version:V1.00
 */
public class ParserAction extends Action {

	private Element element;

	private AbstractClient client = new AbstractClient("http://tu.duowan.com/");

	public ParserAction(ActionQueue queue, Element element) {
		super(queue);
		this.element = element;
	}

	private int num = 1;

	@Override
	public void execute() {
		Elements elements = element.getElementsByTag("a");
		for (Element element : elements) {
			// System.out.println(element);
			String attr = element.attr("href");
			if (attr != null) {
				if (attr.matches("http://tu.duowan.com/lol/gallery/[1-9]\\d*.html")) {
					System.out.println(attr);

					Document document = JsoupRequest.request(attr, true);

					Element element2 = document.getElementById("image-show");

					System.err.println(element2);

				//	Elements byTag = element2.getElementsByTag("img");
				//	System.out.println(byTag);

//					if (byTag != null) {
//						for (Element element3 : byTag) {
//							String jpgurl = element3.attr("src");
//
//							System.out.println(jpgurl);
//
//							HttpEntity httpEntity = client.doGet(jpgurl);
//
//							try {
//								InputStream inputStream = httpEntity.getContent();
//								if(inputStream != null){
//									File file = new File(PropUtils.getString("picSavePath") + (num++) + ".jpg");
//									FileUtils.copyInputStreamToFile(inputStream, file);
//								}
//							} catch (UnsupportedOperationException | IOException e) {
//								e.printStackTrace();
//							}
//						}
//					}

				}
			}
		}
	}

	 public static void main(String[] args) throws Exception{
	        String str;
	        //创建一个webclient
	        WebClient webClient = new WebClient();
	        //htmlunit 对css和javascript的支持不好，所以请关闭之
	        webClient.getOptions().setJavaScriptEnabled(true);
	        webClient.getOptions().setCssEnabled(false);
	        //获取页面
	        HtmlPage page = webClient.getPage("http://tu.duowan.com/lol/gallery/122206.html#p1");

	        System.out.println("为了获取js执行的数据 线程开始沉睡等待");
            Thread.sleep(3000);//主要是这个线程的等待 因为js加载也是需要时间的
	        //获取页面的文本
	        str = page.asXml();
	        System.out.println(str);
	        //关闭webclient
	        webClient.close();
	    }

}
